import { useEffect, useState, useRef } from 'react'
import { useLocation, useNavigate } from 'react-router-dom'
import style from './index.module.scss'
import { Button, Form, Input, TextArea, Switch, Cascader, Toast, Dialog } from 'antd-mobile'
import provinces from "china-division/dist/provinces.json";
import cities from "china-division/dist/cities.json";
import areas from "china-division/dist/areas.json";
import { AddAddress, GetAddressDetail, UpdateAddress, DeleteAddress } from '@/api/address'

import HeaderView from '@/components/Header/index'
import LoadingView from '@/components/Loading/index'

const EditAddress = () => {
  const [flag, setFlag] = useState(true)
  const [loadingCode, setLoadingCode] = useState(1)
  const [visible, setVisible] = useState(false) // 地区选择
  const [options, setOption] = useState<any>([])// 城市选项
  const [inputAreaValue, setInputAreaValue] = useState<any>('')// 城市选项
  const [areaPlaceholder, setAreaPlaceHolder] = useState(false) // 地区选择 placeHolder提示
  const [xz, setXZ] = useState(false) // 默认地址
  const [userInfo, setUserInfo] = useState({name: '', phone: 0, province: '', city: '', county: '', address: '', is_default: 0})
  const location = useLocation()
  const navigate = useNavigate()
  const formEL = useRef<any>(null)

      

  // 地址数据
  const init = async () => {
    if(location.state.type === 'edit') {
      const res = await GetAddressDetail(location.state.id).catch((err) => {
        if (err.code === 'ECONNABORTED' || err.code === 'ERR_NETWORK') setLoadingCode(2)
        if (err.status === 401) Toast.show({icon: 'fail', content: '请先登录呀', maskClickable: false, duration: 1000, afterClose: () => {
          navigate('/login', {state: {fromPath: '/address'}})
        }})
      })

      if(res?.status === 200) {
        setFlag(false)
        setXZ(res.data.is_default === 1 ? true : false)
        setUserInfo({
          name: res?.data.name,
          phone: res?.data.phone,
          province: res?.data.province,
          city: res?.data.city,
          county: res?.data.county,
          address: res?.data.address,
          is_default: res?.data.is_default
        })

        formEL.current.setFieldsValue({
          user: res.data.name,
          tel: res.data.phone,
          detail: res.data.address,
          defaultAddress: res.data.is_default === 1 ? true : false,
        })
        setInputAreaValue(`${res.data.province}-${res.data.city}-${res.data.county}`)
      }
    }
  }

  // 地区数据
  const getArea = () => {
    // 获得区   
    areas.forEach(area => {
      const matchCity: any = cities.filter(city => city.code === area.cityCode)[0];
      if (matchCity) {
        matchCity.children = matchCity.children || [];
        matchCity.children.push({
          label: area.name,
          value: area.name
        })
      }
    })

    // 获得市
    cities.forEach((city: any) => {
      const matchProvince: any = provinces.filter( province => province.code === city.provinceCode)[0];
      if (matchProvince) {
        matchProvince.children = matchProvince.children || [];
        matchProvince.children.push({
          label: city.name,
          value: city.name,
          children: city.children
        })
      }
    })

    const opt = provinces.map((province: any) => ({
      label: province.name,
      value: province.name,
      children: province.children
    }))
    setOption(opt)
  }

  useEffect(() => {
    init()
    getArea()
  }, [])


  // 新增地址 或者 修改地址 或者 删除地址 捕获异常公共方法
  const catchMsg = async (err: {code: string}) => {
    if (err.code === 'ECONNABORTED' || err.code === 'ERR_NETWORK') Toast.show({icon: 'fail', content: '网络加载失败', duration: 1000})
  }

  // 新增地址 或者 修改地址 或者 删除地址 Toast弹框信息公共方法
  const toastMsg = (res: {status: number}, msg: string) => {
    if(res?.status === 201 || res?.status === 204) {
      Toast.show({icon: 'success', content: msg, duration: 1000, afterClose: () => {navigate('/address')}})
    }
  }

  // 新增地址 或者 修改地址
  const onFinish =  async (val: {user: string, tel: number, detail: string, defaultAddress: boolean}) => {
    if(inputAreaValue.length === 0) {
      setAreaPlaceHolder(true)
      return false
    }

    const data = {
      name: val.user,
      phone: val.tel,
      province: inputAreaValue.split('-')[0],
      city: inputAreaValue.split('-')[1],
      county: inputAreaValue.split('-')[2],
      address: val.detail,
      is_default: val.defaultAddress ? 1 : 0
    }

    let res: any = null
    if(location.state.type === 'add') { // 新增地址
      res = await AddAddress(data).catch((err) => { catchMsg(err) })
      toastMsg(res, '添加成功')
    } else { // 修改地址
      if(JSON.stringify(userInfo) === JSON.stringify(data)) {
        navigate('/address')   
      } else {
        res = await UpdateAddress(location.state.id, data).catch((err) => { catchMsg(err) })
        toastMsg(res, '修改成功')
      }
    }
  }

  // 删除地址
  const removeAddress = () => {
    Dialog.confirm({
      content: '确认要删除',
      onConfirm: async () => {
        const res: any = await DeleteAddress(location.state.id).catch((err) => catchMsg(err))
        toastMsg(res, '删除成功')
      }
    })
  }

  // 点击地区选择 请求地区数据 并显示
  const showArea = () => {
    setVisible(true)
  }

  const saveArea = (val: []) => {
    setInputAreaValue(val.join('-'))
  }
  
  return (
    <>
      {/* 头部信息 */}
      <HeaderView title={location.state.type === 'add' ? '新增地址' : '修改地址'} backIcon={true} backPath='address'></HeaderView>

      <div className={style.content}>
        <Form ref={formEL} layout='horizontal' onFinish={onFinish} footer={ 
          <>
            <Button block  type="submit" style={{'--background-color': '#07c160', '--text-color': '#fff', '--border-width': "0px", '--border-radius': '20px', marginBottom: '15px'}}>
              {location.state.type === 'add' ? '保存' : '修改'}
            </Button> 
            <Button block style={{'--border-radius': '20px'}} onClick={() => removeAddress()}>删除</Button>
          </>
        }>
          <Form.Item name='user' label='姓名' rules={[{ required: true, message: '姓名不能为空' }]}>
            <Input placeholder='请输入姓名' />
          </Form.Item>

          <Form.Item name='tel' label='电话' rules={[{ required: true, message: '电话不能为空' }]}>
            <Input placeholder='请输入电话' />
          </Form.Item>

          <Form.Item arrowIcon  label='地区' description={areaPlaceholder && <p style={{color: 'red'}}>请选择地区</p>} onClick={() => showArea()}>
            <Input placeholder='请输入地区' readOnly value={inputAreaValue}/>
            <Cascader options={options} visible={visible} onClose={() => { setVisible(false) }} onConfirm={(val: any) => saveArea(val)}/>
          </Form.Item>

          <Form.Item name='detail' label='详细地址' rules={[{ required: true, message: '详细地址不能为空' }]}>
            <TextArea placeholder='请输入详细地址' />
          </Form.Item>

          <Form.Item name='defaultAddress' label='设置为默认地址'>
            <Switch onChange={(val: boolean) => setXZ(val)} checked={xz}/>
          </Form.Item>
        </Form>
      </div>

      {/* 加载中或者加载超时 */}
      {location.state.type === 'edit' && flag && <LoadingView loadingCode={loadingCode}></LoadingView>}
    </>
  )
}

export default EditAddress